﻿using ExcelSystem.Event;
using ExcelSystem.Model;
using ExcelSystem.ToolClass;
using ExcelSystem.ToolHelper;
using ExcelSystem.ViewModelsClass;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ExcelSystem.ViewModels
{
    public class OrderListViewModel : BindableBase
    {
        ExcelContext db;

        private ObservableCollection<MaterialViewModel> ordersModel;
        /// <summary>
        /// 页面主数据
        /// </summary>
        public ObservableCollection<MaterialViewModel> OrdersModel
        {
            get { return ordersModel; }
            set { SetProperty(ref ordersModel, value); }
        }

        private OrderFilter orderFilter;

        /// <summary>
        /// 查询条件
        /// </summary>
        public OrderFilter OrderFilter
        {
            get { return orderFilter; }
            set { SetProperty(ref orderFilter, value); }
        }

        private List<Company> companys;

        /// <summary>
        /// 公司
        /// </summary>
        public List<Company> Companys
        {
            get { return companys; }
            set { SetProperty(ref companys, value); }
        }

        private Visibility importVisibility;

        /// <summary>
        /// 导入
        /// </summary>
        public Visibility ImportVisibility
        {
            get { return importVisibility; }
            set { SetProperty(ref importVisibility, value); }
        }

        private Visibility exportVisibility;

        /// <summary>
        /// 导出
        /// </summary>
        public Visibility ExportVisibility
        {
            get { return exportVisibility; }
            set { SetProperty(ref exportVisibility, value); }
        }

        private Visibility allVisibility;

        /// <summary>
        /// 总表
        /// </summary>
        public Visibility AllVisibility
        {
            get { return allVisibility; }
            set { SetProperty(ref allVisibility, value); }
        }




        private DelegateCommand<string> openExcelCommand;
        public DelegateCommand<string> OpenExcelCommand
        {
            get { return openExcelCommand; }
            set { SetProperty(ref openExcelCommand, value); }
        }

        private DelegateCommand exportExcelCommand;
        public DelegateCommand ExportExcelCommand
        {
            get { return exportExcelCommand; }
            set { SetProperty(ref exportExcelCommand, value); }
        }

        private DelegateCommand exportExcelInfoCommand;
        public DelegateCommand ExportExcelInfoCommand
        {
            get { return exportExcelInfoCommand; }
            set { SetProperty(ref exportExcelInfoCommand, value); }
        }
        private DelegateCommand searchCommand;
        public DelegateCommand SearchCommand
        {
            get { return searchCommand; }
            set { SetProperty(ref searchCommand, value); }
        }

        private DelegateCommand<string> nextCommand;
        public DelegateCommand<string> NextCommand
        {
            get { return nextCommand; }
            set { SetProperty(ref nextCommand, value); }
        }

        private DelegateCommand<object> changeFilterCommand;
        public DelegateCommand<object> ChangeFilterCommand
        {
            get { return changeFilterCommand; }
            set { SetProperty(ref changeFilterCommand, value); }
        }

        private DelegateCommand filterCommand;
        public DelegateCommand FilterCommand
        {
            get { return filterCommand; }
            set { SetProperty(ref filterCommand, value); }
        }

        private DelegateCommand<string> clipboardCommand;

        /// <summary>
        /// 复制按钮
        /// </summary>
        public DelegateCommand<string> ClipboardCommand
        {
            get { return clipboardCommand; }
            set { SetProperty(ref clipboardCommand, value); }
        }

        private readonly IEventAggregator eventAggregator;
        private readonly IRegionManager regionManage;
        private readonly IDialogService dialogService;
        public OrderListViewModel(IRegionManager regionManage, IDialogService dialogService, IEventAggregator eventAggregator)
        {
            //数据库文档
            db = ExcelContentFactory.GetInstance();
            //依赖注入
            this.regionManage = regionManage;
            this.dialogService = dialogService;
            this.eventAggregator = eventAggregator;
            OrdersModel = new ObservableCollection<MaterialViewModel>();
            ExcelUserHelper.Init();
            OpenExcelCommand = new DelegateCommand<string>(OpenExcel);
            FilterCommand = new DelegateCommand(OpenFilter);
            SearchCommand = new DelegateCommand(GetOrdersModel);
            ChangeFilterCommand = new DelegateCommand<object>(ChangeFilter);
            NextCommand = new DelegateCommand<string>(Next);

            ExportExcelCommand = new DelegateCommand(ExportExcel);
            ExportExcelInfoCommand = new DelegateCommand(ExportExcelInfo);
           


            Init();
            //ExportExcelInfo();

        }

        private void OpenExcel(string obj)
        {
            //西奥
            if(obj=="1")
            {
                eventAggregator.GetEvent<GetInputMessages>().Publish(ExcelUserHelper.ImportExcelSystem());
            }
            //优麦 订单
            if (obj == "2")
            {
                MessageBox.Show("可多选订单表");
                eventAggregator.GetEvent<GetInputMessages>().Publish(ExcelUserHelperYM.ReadExcelYM());
            }
            //优麦 物料
            if (obj == "2.1")
            {
                MessageBox.Show("导入之前可以去掉表格中的所有筛选，避免数据导入遗漏");
                eventAggregator.GetEvent<GetInputMessages>().Publish(ExcelUserHelperYM.ReadExcelYM_MaterialNo());
            }

            GetOrdersModel();
        }

        private void Next(string obj)
        {
            if(obj=="1")
            {
                OrderFilter.CurrentPage++;
                if (OrderFilter.CurrentPage > OrderFilter.AllPage )
                {
                    OrderFilter.CurrentPage--;
                    MessageBox.Show($"超出页码范围，请输入1-{OrderFilter.AllPage}的数字");
                }
            }
            else
            {
                OrderFilter.CurrentPage--;
                if (OrderFilter.CurrentPage <= 0)
                {
                    OrderFilter.CurrentPage++;
                    MessageBox.Show($"超出页码范围，请输入1-{OrderFilter.AllPage}的数字");
                }
            }
            GetOrdersModel();
        }




        /// <summary>
        /// 打印
        /// </summary>
        private void ExportExcel()
        {
            var list = OrdersModel.Where(t => t.IsSelected == true).ToList();
            string warn = "";
            //优迈导出
            if(OrderFilter.Company==2)
            {
                var no_list= list.Where(t => !string.IsNullOrEmpty(t.Material.MaterialSpecifications)).Select(t=>t.Material.MaterialNo).ToList();
                //检查是否是组合件
                var bom= db.BOMs.FirstOrDefault(t => (no_list[0] == t.MaterialNo && no_list[1] == t.ChildMaterialNo)
                || (no_list[1] == t.MaterialNo && no_list[0] == t.ChildMaterialNo)
                );
                if(bom==null)
                {
                    MessageBox.Show(no_list[0] + "未创建BOM，请先补全BOM表");
                }
                else
                {

                    ExcelUserHelperYM.PrintingYM(list.Where(t => !string.IsNullOrEmpty(t.Material.MaterialSpecifications)).ToList(), dialogService, bom);
                }


            }
            else
            {

                list.ForEach(t =>
                {

                    var b = db.BOMs.FirstOrDefault(f => f.MaterialNo == t.Material.MaterialNo);
                    if (b == null)
                    {
                        warn += t.Material.MaterialNo + ",";
                    }
                });
                if (!string.IsNullOrEmpty(warn) || OrdersModel[0].Material.MaterialNo.Contains("FB"))
                {
                    if (OrdersModel[0].Material.MaterialNo.Contains("FB"))
                    {
                        MessageBox.Show(warn + "有非标物件请先检查非标参数");
                        PrintingXiAo_FB();
                        ExcelUserHelper.PrintingXiAo(list, dialogService);
                    }
                    else
                    {
                        MessageBox.Show(warn + "未创建BOM，请先补全BOM表");
                    }

                    return;
                }
                ExcelUserHelper.PrintingXiAo(list, dialogService);
            }

           
        }
        /// <summary>
        /// 西奥非标
        /// </summary>
        /// <param name="material"></param>
        public  void PrintingXiAo_FB()
        {
            foreach (MaterialViewModel materialViewModel in OrdersModel)
            {
                DialogParameters dialogParameters = new DialogParameters();
                dialogParameters.Add("data", materialViewModel);
                //弹出本体属性
                dialogService.ShowDialog("BOMAdd", dialogParameters, null);



            }

        }
        /// <summary>
        /// 数据初始化
        /// </summary>
        private void Init()
        {
            Companys = new List<Company>();
            Companys.Add(new Company() {  Id=1, Name="西奥"});
            Companys.Add(new Company() { Id = 2, Name = "优麦" });

            OrderFilter = new OrderFilter();
            OrderFilter.CurrentPage = 1;
            OrderFilter.PageSize = 50;
            GetOrdersModel();
        }

        /// <summary>
        /// 打开筛选界面
        /// </summary>
        private void OpenFilter()
        {
            dialogService.Show("MaterialFilter");
            //dialogService.Show("BOMAdd");
        }

        /// <summary>
        /// 修改筛选条件
        /// </summary>
        /// <param name="obj"></param>
        private void ChangeFilter(object obj)
        {
            if (obj != null)
            {
                List<string> filter = new List<string>();
                object[] objects = obj as object[];
                foreach (var item in objects)
                {
                    filter.Add(item.ToString());
                }

                if (filter != null && filter.Count() == 2)
                {
                    switch (filter[0])
                    {
                        case "MaterialNo":
                            OrderFilter.MaterialNo = filter[1]; OrderFilter.CurrentPage = 1;
                            break;
                        case "OrderNo":
                            OrderFilter.OrderNo = filter[1]; OrderFilter.CurrentPage = 1;
                            break;
                        case "ContractNo":
                            OrderFilter.ContractNo = filter[1]; OrderFilter.CurrentPage = 1;
                            break;
                        case "PageSize":
                            int cp = 0;
                            bool result = int.TryParse(filter[0], out cp);
                            if (result)
                            {
                                if (cp > OrderFilter.AllPage || cp <= 0)
                                {
                                    MessageBox.Show($"超出页码范围，请输入1-{OrderFilter.AllPage}的数字");
                                }
                            }
                            else
                            {
                                MessageBox.Show("请输入纯数字");
                            }
                            OrderFilter.PageSize = Convert.ToInt32(filter[1]);
                            break;
                        case "AllPage":
                            OrderFilter.AllPage = Convert.ToInt32(filter[1]);
                            break;
                        case "Count":
                            OrderFilter.Count = Convert.ToInt32(filter[1]);
                            break;
                        case "CurrentPage":
                            if(string.IsNullOrEmpty(filter[1]))
                            {
                                OrderFilter.CurrentPage = Convert.ToInt32(1);
                            }
                            else
                            {
                                OrderFilter.CurrentPage = Convert.ToInt32(filter[1]);
                            }
                          
                            break;

                    }

                }


            }
            GetOrdersModel();
        }


        /// <summary>
        /// 获取数据
        /// </summary>
        public void GetOrdersModel()
        {
            //获取Order
            var order = db.Orders.Where(t => t == t);
            if (OrderFilter.OrderNo != null)
                order = order.Where(t => t.OrderNo.Contains(OrderFilter.OrderNo));
            if (OrderFilter.SchedulingDate_begin != null)
                order = order.Where(t => t.SchedulingDate >= OrderFilter.SchedulingDate_begin);
            if (OrderFilter.SchedulingDate_end != null)
                order = order.Where(t => t.SchedulingDate <= OrderFilter.SchedulingDate_end);
            if (OrderFilter.DeliveryDate_begin != null)
                order = order.Where(t => t.DeliveryDate >= OrderFilter.DeliveryDate_begin);
            if (OrderFilter.DeliveryDate_end != null)
                order = order.Where(t => t.DeliveryDate <= OrderFilter.DeliveryDate_end);
            if (OrderFilter.CreatedTime != null)
                order = order.Where(t => t.CreateTime.DayOfYear == OrderFilter.CreatedTime.Value.DayOfYear);
            if (OrderFilter.Company != 0&& OrderFilter.Company != 1)
                order = order.Where(t => t.Company == OrderFilter.Company);
            
            var order_result = order.ToList();
            //获取所有下属物料表
            var materials = db.Materials.Where(t => order_result.Select(t => t.OrderNo).ToList().Contains(t.OrderNo));
            //条件筛选 从表
            if (!string.IsNullOrEmpty(OrderFilter.MaterialNo))
                materials = materials.Where(t => t.MaterialNo.Contains(OrderFilter.MaterialNo.Trim()));
            if (!string.IsNullOrEmpty(OrderFilter.OrderNo))
                materials = materials.Where(t => t.OrderNo.Contains(OrderFilter.OrderNo.Trim()));
            if (!string.IsNullOrEmpty(OrderFilter.ContractNo))
                materials = materials.Where(t => t.ContractNo.Contains(OrderFilter.ContractNo.Trim()));



            OrdersModel.Clear();
            //组合 筛选
            var list = materials.ToList();

            var temp = new List<MaterialViewModel>();
            if(orderFilter.Company==2)
            {
                order_result.ForEach(t =>
                {
                    var list_temp = list.Where(m => m.OrderNo == t.OrderNo && m.ContractNo == t.ContractNo && m.BoxNumner == (t.MaterialDescribe == "承重钢梁" ? "18#" : "35#"));
                foreach (var item in list_temp)
                    {
                        if(string.IsNullOrEmpty(item.MaterialSpecifications))
                        {
                            item.MaterialSpecifications = item.Remarks;
                        }
                        
                        temp.Add(new MaterialViewModel()
                        {
                            DeliveryDate = t.DeliveryDate,
                            SchedulingDate = t.SchedulingDate,
                            CreateTime = t.CreateTime,
                            Material = item,
                            Factory = t.Factory
                        });
                    }
                });
            }
            else
            {
                order_result.ForEach(t =>
                {
                    foreach (var item in list.Where(m => m.OrderNo == t.OrderNo && m.ContractNo == t.ContractNo))
                    {
                        temp.Add(new MaterialViewModel()
                        {
                            DeliveryDate = t.DeliveryDate,
                            SchedulingDate = t.SchedulingDate,
                            CreateTime = t.CreateTime,
                            Material = item,
                            Factory = t.Factory
                        });
                    }
                });
            }
           
            temp = temp.OrderByDescending(t => t.SchedulingDate).ThenBy(t => t.Material.ContractNo).ToList();

            OrderFilter.Count = temp.Count();
            OrderFilter.AllPage = OrderFilter.Count / OrderFilter.PageSize + 1;
            OrdersModel.AddRange(temp.Skip((OrderFilter.CurrentPage - 1) * orderFilter.PageSize).Take(orderFilter.PageSize));

            //从BOM表中补全数据 

            foreach (var item in OrdersModel)
            {
                var bom = db.BOMs.FirstOrDefault(t => t.MaterialNo == item.Material.MaterialNo);
                if (bom != null)
                {
                    item.WireRopeHole = bom.WireRopeHole;
                    item.Material.Direction = bom.Direction;
                }

            }



        }


        /// <summary>
        ///  导出总表
        /// </summary>
        private void ExportExcelInfo()
        {
            //获取Order
            var order = db.Orders.Where(t => t == t);
            if (OrderFilter.OrderNo != null)
                order = order.Where(t => t.OrderNo.Contains(OrderFilter.OrderNo));
            if (OrderFilter.SchedulingDate_begin != null)
                order = order.Where(t => t.SchedulingDate >= OrderFilter.SchedulingDate_begin);
            if (OrderFilter.SchedulingDate_end != null)
                order = order.Where(t => t.SchedulingDate <= OrderFilter.SchedulingDate_end);
            if (OrderFilter.DeliveryDate_begin != null)
                order = order.Where(t => t.DeliveryDate >= OrderFilter.DeliveryDate_begin);
            if (OrderFilter.DeliveryDate_end != null)
                order = order.Where(t => t.DeliveryDate <= OrderFilter.DeliveryDate_end);
            if (OrderFilter.Company != 0 && OrderFilter.Company != 1)
                order = order.Where(t => t.Company == OrderFilter.Company);
            var order_result = order.ToList();

           var orders=  order_result.GroupBy(t => t.OrderNo);


            var contractNos =  order_result.Select(t => t.ContractNo).Distinct().ToList();

            //打印总表
            if (OrderFilter.Company == 2)
            {
                //ExcelUserHelperYM.ReadBOM();
                ExcelUserHelperYM.PrintingYMAll(order_result);
            }
            else
            {
                //补充建议BOM
                var notbom = db.Materials.Where(t => contractNos.Contains(t.ContractNo)).Select(t => t.MaterialNo).Where(t =>
                !db.BOMs.Select(b => b.MaterialNo).Contains(t)
                ).Distinct().ToList();
                DialogParameters parameters = new DialogParameters();
                parameters.Add("id", notbom);
                if (notbom.Count > 0)
                {
                    dialogService.ShowDialog("BOMAddList", parameters, null);
                }
                ExcelUserHelper.PrintingXiAoAll(order_result);
            }
          
               
         
          
         





        }


      

    }
}
